<%@ page language="java" contentType="text/html;charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ include file="import.jsp"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<h3 class="heading">
	<c:choose>
		<c:when test="${query != null && query.id != null}">Custom query</c:when>
	    <c:otherwise>New query</c:otherwise>
	</c:choose>
</h3>
<form id="query_form" method="post">
	<div >
		<label class="control-label">Name<span class="f_req">*</span></label> 
		<input type="text" class="span4" id="name" name="name" maxlength="100" placeholder="name" <c:if test="${query != null}">value="${query.name}"</c:if>/>
	</div>
	<div>
		<label class="checkbox"> 
		<input type="checkbox" id="iscommon" value="option1" name="iscommon" <c:if test="${query != null && query.iscommon eq 'Y'}"> checked="checked"</c:if>>公用
		</label>
	</div>
	<fieldset id="filters">
	<legend class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapseOne"><small><spring:message code="Filters"/></small></legend>
	<div style="" id="collapseOne" class="accordion-body collapse in">
		<div class="span8">
				<table id="search">	
					<c:forEach items="${search}" var="t" varStatus="status">
						<tr style="<c:if test="${t.isShow eq 'false'}">display:none;</c:if>" id="tr_${ t.dbfield }" class="filter">
						    <td style="width:200px;">
						    	<label class="checkbox" for="cb_${ t.dbfield }">
						        <input id="cb_${ t.dbfield }" name="cb_${ t.dbfield }" onclick="toggle_filter('${ t.dbfield }');" type="checkbox" value="${ t.dbfield }" <c:if test="${t.isShow eq 'true'}"> checked="checked"</c:if>/>
						        <spring:message code="${ t.name }"/></label>
						    </td>
						    <td style="width:150px;">
						        <select class="select-small" id="operators_${ t.dbfield }" name="operators_${ t.dbfield }" onchange="toggle_operator('${ t.dbfield }');" style="vertical-align: top;">
						        	<c:forEach items="${t.compares}" var="list" varStatus="status">
						        		<option value="${list}" <c:if test="${t.comparesvalue != null && t.comparesvalue == list}">selected</c:if>>${list}</option>
						        	</c:forEach>
								</select>
						    </td>
						    <td>    
							    <div id="div_values_${ t.dbfield }">
							    	<input id="type_${ t.dbfield }" name = "type_${ t.dbfield }" type="hidden" value="${t.valuetype}" />
							    	<c:choose>
									    <c:when test="${t.valuetype == '4' || t.valuetype == '3'}">
									      	<select name="values_${ t.dbfield }" id="values_${ t.dbfield }" class="select-small" style="vertical-align: top;" <c:if test="${t.isMultSelect eq 'true'}">multiple="multiple"</c:if>>
												<c:forEach items="${t.mapValues}" var="entry" varStatus="status">
													<c:set var="b_key" value=",${entry.key}"/>
													<c:set var="e_key" value="${entry.key},"/>
													<option value="${entry.key}" <c:if test="${t.valuevalue eq entry.key || fn:contains(t.valuevalue, b_key) || fn:contains(t.valuevalue, e_key)}">selected</c:if>>${entry.value}</option>
												</c:forEach>
											</select>
											<a href="#" onclick="toggle_multi_select('${ t.dbfield }'); return false;" style="vertical-align: bottom;">
												<i class="splashy-bullet_blue_expand"></i>
											</a>
									    </c:when>
									    <c:when test="${t.valuetype == '2'}">
										      	<input class="select-small" id="values_start${ t.dbfield }" name="values_start${ t.dbfield }" type="date" <c:if test="${t.startDate != null}">value="${t.startDate}"</c:if>/>
										      	<input class="select-small" id="values_end${ t.dbfield }" name="values_end${ t.dbfield }" type="date" <c:if test="${t.endDate != null}">value="${t.endDate}"</c:if>/>
										</c:when>
									    <c:otherwise>
									    	<input class="select-small" id="values_${ t.dbfield }" name="values_${ t.dbfield }" size="30" type="text" <c:if test="${t.valuevalue != null}">value="${t.valuevalue}"</c:if>/>
									    </c:otherwise>
									</c:choose>
							    </div>
						    </td>
				    	</tr>
					</c:forEach>
				</table>
			</div>
			<div class="span4">
				<label for="add_filter_select" class="checkbox">添加搜索条件: 
				<select class="select-small" id="add_filter_select"
					onchange="add_filter();">
						<option value=""></option>
						<c:forEach items="${search}" var="t" varStatus="status">
							<option value="${ t.dbfield }" <c:if test="${t.isShow eq 'true'}"> disabled="disabled"</c:if>><spring:message code="${ t.name }"/></option>
						</c:forEach>
						</select>
				</label>
			</div>
		<input id="f_" name="f[]" type="hidden" value="" />
		<input id="node" name="node" type="hidden" value="${node}" />
		<input id="fields" name="fields" type="hidden" value="${fields}" />
		<c:if test="${query != null && query.id != null}">
		<input id="id" name="id" type="hidden" value="${query.id}" />
		</c:if>
	</div>
	</fieldset>

	<fieldset id="options">
		<legend class="accordion-toggle" data-toggle="collapse" data-parent="#accordion2" href="#collapseTwo"><small>Options</small></legend>
		<div style="" id="collapseTwo" class="accordion-body collapse in">
		<table>
    		<tr>
    			<td>Columns</td>
				<td>
				<table style="border-collapse: collapse; border:0;">
				<tr>
					<td style="padding-left:0">
						<select multiple="multiple" id="available_columns" name="available_columns">
							<c:forEach items="${unselect}" var="s" varStatus="status">
								<c:if test="${s ne ''}">
									<option value="${ s }"><spring:message code="${ s }"/></option>
								</c:if>
							</c:forEach>
						</select>
					</td>
					<td align="center" valign="middle">
						<i class="splashy-arrow_medium_left" onclick="leftOptions()"></i>
						<i class="splashy-arrow_medium_right" onclick="rightOptions()"></i>
					</td>
					<td>
						<select multiple="multiple" id="selected_columns" name="selected_columns"> 
							<c:forEach items="${select}" var="s" varStatus="status">
								<option value="${ s }"><spring:message code="${ s }"/></option>
							</c:forEach>
						</select>
					</td>
					<td align="center" valign="middle">
						<i class="splashy-arrow_medium_up" onclick="upOptions()"></i>
						<i class="splashy-arrow_medium_down" onclick="downOptions()"></i>
					</td>
				</tr>
				</table>
				</td>
			</tr>
		</table>
		</div>
	</fieldset>
	<div class="form-actions">
		<button class="btn btn-inverse" type="submit">Save</button>
	</div>
</form>
<script src="js/jquery.min.js"></script>
<script>
	function add_filter() {
	    select = $("#add_filter_select");
	    field0 = select.val();
	    field = field0.replace(".","\\."); 
	    count= $("#add_filter_select option").length;
	    $("#cb_"+field).attr('checked',true);
	    $("#tr_"+field).show();
	    toggle_filter(field);
	    select.get(0).selectedIndex = 0;
	    
	    for (i=0; i<count; i++) {
	        if (select.get(0).options[i].value == field0) {
	        	select.get(0).options[i].disabled = "disabled";
	        }    
	    }
	}
	
	function toggle_filter(field) {
		field = field.replace(".","\\."); 
	    check_box = $('#cb_' + field);
	    type = $('#type_' + field).val();
	    
	    if (check_box.attr("checked") == 'checked') {
	    	$("#operators_"+field).show();
	    	if (type == '2') {
	    		$("#values_start"+field).show();
	    		$("#values_end"+field).show();
	    	} else {
	    		$("#values_"+field).show();
	    		if (type == '3' || type == '4') {
	    			$("#multi_"+field).show();
	    		}
	    	}
	    	$("#cb_"+field).attr('checked',true);
	        //toggle_operator(field);
	    } else {
	    	$("#operators_"+field).hide();
	    	if (type == '2') {
	    		$("#values_start"+field).hide();
	    		$("#values_end"+field).hide();
	    	} else {
	    		$("#values_"+field).hide();
	    		if (type == '3' || type == '4') {
	    			$("#multi_"+field).hide();
	    		}
	    	}
	    	$("#cb_"+field).removeAttr('checked');
	  }
	}
	
	function toggle_multi_select(field) {
		field = field.replace(".","\\."); 
	    select = $('#values_' + field);
	    if (select.attr("multiple")== "multiple") {
	        select.removeAttr("multiple");
	    } else {
	    	select.attr("multiple","multiple");
	    }
	}
	
	function leftOptions() {
		$("#selected_columns").find('option:selected').each(function(){
			$("#available_columns").append("<option value='" + $(this).val() + "'>" + $(this).html() + "</option>");
			$(this).remove();
		});
	}
	
	function rightOptions() {
		$("#available_columns").find('option:selected').each(function(){
			$("#selected_columns").append("<option value='" + $(this).val() + "'>" + $(this).html() + "</option>");
			$(this).remove();
		});
	}
	
	function upOptions() {
		var $opt = $("#selected_columns option:selected:first");
		if (!$opt.length) return;   
		$opt.prev().before($opt);
	}
	
	function downOptions() {
		var $opt = $("#selected_columns option:selected:first");   
		if (!$opt.length) return;   
		$opt.next().after($opt);
	}
	
	$(document).ready(function(){
		$('#query_form').validate({
			onkeyup: false,
			errorClass: 'error',
			validClass: 'valid',
			highlight: function(element) {
				$(element).closest('div').addClass("f_error");
			},
			unhighlight: function(element) {
				$(element).closest('div').removeClass("f_error");
			},
            errorPlacement: function(error, element) {
                // Set positioning based on the elements position in the form
			var elem = $(element);
			
			// Check we have a valid error message
			if(!error.is(':empty')) {
				if( (elem.is(':checkbox')) || (elem.is(':radio')) ) {
					// Apply the tooltip only if it isn't valid
					elem.filter(':not(.valid)').parent('label').parent('div').find('.error_placement').qtip({
						overwrite: false,
						content: error,
						position: {
							my: 'left bottom',
							at: 'center right',
							viewport: $(window),
							adjust: {
								x: 6
							}
						},
						show: {
							event: false,
							ready: true
						},
						hide: false,
						style: {
							classes: 'ui-tooltip-red ui-tooltip-rounded' // Make it red... the classic error colour!
						}
					})
					// If we have a tooltip on this element already, just update its content
					.qtip('option', 'content.text', error);
				} else {
					// Apply the tooltip only if it isn't valid
					elem.filter(':not(.valid)').qtip({
						overwrite: false,
						content: error,
						position: {
							my: 'bottom left',
							at: 'top right',
							viewport: $(window),
                            adjust: { x: -8, y: 6 }
						},
						show: {
							event: false,
							ready: true
						},
						hide: false,
						style: {
							classes: 'ui-tooltip-red ui-tooltip-rounded' // Make it red... the classic error colour!
						}
					})
					// If we have a tooltip on this element already, just update its content
					.qtip('option', 'content.text', error);
				};
                
			}
			// If the error is empty, remove the qTip
			else {
				if( (elem.is(':checkbox')) || (elem.is(':radio')) ) {
					elem.parent('label').parent('div').find('.error_placement').qtip('destroy');
				} else {
					elem.qtip('destroy');
				}
			}
            },
            rules: {
				name: { required: true}
			},
            invalidHandler: function(form, validator) {
				$.sticky("There are some errors. Please corect them and submit again.", {autoclose : 5000, position: "top-right", type: "st-error" });
			},
			submitHandler : function(form){
				if ($("#id").val()== null) {
					$("#query_form").attr('action', $("#node").val()+'savequery');
				} else {
					$("#query_form").attr('action', $("#node").val()+'editquery');
				}
				var count=$("#selected_columns option").length;
				for(var i=0;i<count;i++)  {           
			       $("#selected_columns").get(0).options[i].selected = true;
				};
				count=$("#available_columns option").length;
				for(var i=0;i<count;i++)  {           
			       $("#available_columns").get(0).options[i].selected = true;
				};
		    	form.submit();
			}
        });
	});
</script>